package org.example.cart;

import org.example.Strategy.OrderDiscountStrategy;
import org.example.domain.CartItem;
import org.example.domain.Product;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

//购物车类
public class ShoppingCart {
    private final List<CartItem> items = new ArrayList<>();
    private OrderDiscountStrategy orderDiscountStrategy;

    public void addItem(Product product, int quantity) {
        items.add(new CartItem(product, quantity));
    }

    public void setOrderDiscount(OrderDiscountStrategy strategy) {
        this.orderDiscountStrategy  = strategy;
    }

    public BigDecimal calculateTotal() {
        BigDecimal subtotal = items.stream()
                .map(CartItem::calculateSubtotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .setScale(2, RoundingMode.HALF_UP);

        return orderDiscountStrategy != null ? orderDiscountStrategy.apply(subtotal) : subtotal;
    }

}
